package pers.qianyu.month_202012.date_20201217;

import java.util.*;

/**
 * 875. 爱吃香蕉的珂珂
 * https://leetcode-cn.com/problems/koko-eating-bananas/
 *
 * @author mizzle rain
 * @date 2020-12-17 21:49
 */
public class MinEatingSpeed {
    public int minEatingSpeed(int[] piles, int H) {
        int len = piles.length;
        Arrays.sort(piles);
        int left = 1, right = piles[len - 1];
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            long cost = cost(piles, mid);
            if (cost <= H) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    private long cost(int[] piles, int speed) {
        long cost = 0;
        for (int pile : piles) {
            int a = pile / speed;
            if (pile % speed == 0) {
                cost += a;
            } else {
                cost = cost + a + 1;
            }
        }
        return cost;
    }
}
